<?php
namespace Services\Upload;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Services\BaseService;
use Services\Log\LogService;
use Services\Upload\Exceptions\UploadException;
use Services\Upload\Interfaces\UploadInterface;
use Think\Log;

class UploadService extends BaseService implements UploadInterface
{

    public function uploadSingle()
    {
        // TODO: Implement uploadSingle() method.
    }

    public function getUploadSign()
    {
        try {
            $expire = time() + 600;
            $qiniuConfig = get_oss_config();
            $uploadScene = $this->getParam('scene', '');
            //进行前置校验
            //1.构造上传策略：
            $dir = date("Ymd");
            $path = $uploadScene . '/' . $dir . "/" . $this->getParam('filename');
            $putPolicy = [
                "scope" => $qiniuConfig["bucket"] . ":" . $path,
                "deadline" => $expire,
                "returnBody" => <<<a
{
      "name": $(fname),
      "etag": $(etag),
      "size": $(fsize),
      "key": $(key),
      "w": $(imageInfo.width),
      "h": $(imageInfo.height),
      "hash": $(etag),
      "link":$(x:link)
}
a
            ];
            $auth = new Auth($qiniuConfig["accessKey"], $qiniuConfig["secretKey"]);
            return [
                "token" => $auth->uploadToken($qiniuConfig["bucket"], $path, $expire, $putPolicy),
                "host" => "https://upload-z2.qiniup.com",//upload.qiniup.com 上传域名适用于华东空间。华北空间使用 upload-z1.qiniup.com，华南空间使用 upload-z2.qiniup.com，北美空间使用 upload-na0.qiniup.com。
                "dir" => $dir,
                "key" => $path,
                "link" => $qiniuConfig["domain"] . "/" . $path,
            ];
        } catch (\Exception $e) {
            LogService::write(format_exception($e), '上传令牌获取', Log::ERR);
        }
    }

    public function uploadFile(){
        $qiniuConfig = get_oss_config();
        $auth = new Auth($qiniuConfig["accessKey"], $qiniuConfig["secretKey"]);
        $uploadToken = $auth->uploadToken($qiniuConfig["bucket"]);
        $manage = new UploadManager();
        $fileName = $this->getParam('filename');
        $templateFileRes = $this->makeTempFile();
        list($uploadResult, $error) = $manage->putFile($uploadToken,$fileName,$templateFileRes['temp_path']);
        return empty($error) ? OssFileService::getOssUrl($fileName) : false;
    }

    /**
     * 创建一个临时文件，并返回临时文件路径信息
     * @return array|void
     */
    private function makeTempFile()
    {
        $tempFile = tmpfile();
        if ($tempFile) {
            // 获取文件的元数据，包括文件路径
            $metaData = stream_get_meta_data($tempFile);
            $tempFilePath = $metaData['uri'];
            // 向临时文件中写入二进制数据
            $binaryData = $this->getParam('content'); // 示例二进制数据，这里是 "Hello World" 的十六进制表示
            fwrite($tempFile, $binaryData);
            return [
                'temp_file' => $tempFile,
                'temp_path' => $tempFilePath
            ];
        } else {
            throw new UploadException('创建临时文件失败');
        }
    }
}
